package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.common.R;
import com.qf.pojo.Student;
import com.qf.service.StudentService;
import com.qf.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @date 2022/4/1
 * @desc
 */
@WebServlet("/studentsPageData")
public class StudentsListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json; charset=UTF-8");


        // 接受模糊查询的数据
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");


        Student student = new Student();
        student.setName(name);
        student.setSex(sex);
        student.setAddress(address);
        student.setPhone(phone);


        String page = req.getParameter("page");
        String limit = req.getParameter("limit");

        StudentService studentService = new StudentServiceImpl();

        /**
         * 因为 前端  layui 的  数据列表 接受的数据格式  默认是
         * {
         *   "code": 0,
         *   "msg": "",
         *   "count": 1000,
         *   "data": [{}, {}]
         * }
         * 所以 后台需要拼一个这样的 JSON串
         * 所以 咱们定义了 一个 R  类
         *
         *     private Integer code;
         *
         *     private String msg;
         *
         *     private T data;
         *
         *     private long count;
         *
         *  利用 fastjson 等 工具类  直接把 java 对象转为 json 格式的字符串 返回给前端
         *  前端能够自动解析
         * */

        // 把接受的 字符串类型的  页码page   和 每页显示的记录数  limit 转为 int 类型
        int pageNum = Integer.parseInt(page);
        int pageSize = Integer.parseInt(limit);

        R<List<Student>> r = studentService.getPageData(pageNum,pageSize,student);

        //R<List<Student>> r = new R();
        //
        //r.setData(students);
        //r.setMsg("学生列表数据");
        //r.setCode(0);   //  layui 接受的成功的 状态码  默认是 0
        //r.setCount(2);

        //fastjson 把 java 对象 转为 json 串
        String s = JSON.toJSONString(r);
        
        // 可以使用下面的工具类
        //String s = FastJsonUtils.convertObjectToJSON(r);
        resp.getWriter().println(s);


    }
}
